<!-- 设备维修-维修申报页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form
        ref="searchFormRef"
        class="custom-form-ui equip-form"
        :model="queryParams"
        label-position="right"
        label-width="120px"
        style="padding-top: 10px"
      >
        <CustomTabs v-model:activeName="activeName" :tabList="tabList" @tabSelect="handelTabSelected" />
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="任务名称/编号" prop="workOrderNameOrCode">
              <px-input
                v-model="queryParams.workOrderNameOrCode"
                placeholder="请输入任务名称/编号"
                maxlength="50"
                clearable
                @blur="queryParams.workOrderNameOrCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备名称/编码" prop="eqpNameOrCode">
              <px-input
                v-model="queryParams.eqpNameOrCode"
                placeholder="请输入设备名称/编码"
                maxlength="50"
                clearable
                @blur="queryParams.eqpNameOrCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <EquipSystemTree
              :className="queryParams.className"
              :systemCode="queryParams.systemCode"
              @changeAllSystemCodes="changeAllSystemCodes"
              @changeSystemCodes="changeSystemCodes"
              @clearSystem="clearSystem"
            />
          </px-col>
          <px-col :span="6">
            <px-form-item label="故障类型" prop="faultTypes">
              <px-cascader
                ref="cascaderRef"
                v-model="queryParams.faultTypes"
                :props="{ value: 'faultTypeCode', label: 'name', checkStrictly: true }"
                :options="faultTypeList"
                placeholder="请选择故障类型"
                clearable
                filterable
                @change="handleTypeChange"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="故障等级" prop="faultLevel">
              <px-select v-model="queryParams.faultLevel" placeholder="请选择故障等级" clearable filterable>
                <px-option v-for="item in faultLevelList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="故障来源" prop="maintenanceSource">
              <px-select v-model="queryParams.maintenanceSource" placeholder="请选择故障来源" clearable filterable>
                <px-option v-for="item in faultSourceList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="状态" prop="workOrderStatusList">
              <px-select
                v-model="queryParams.workOrderStatusList"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                placeholder="请选择状态"
                clearable
                filterable
              >
                <px-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn-flex">
        <px-button v-if="activeName === 1 || activeName === 0" v-has="'ALL_EQUIP_MAINTAIN_TASK_ADD'" icon="Plus" type="primary" @click="handleAdd">
          新建维修任务
        </px-button>
        <div>
          <px-button type="primary" class="mr-2" @click="queryTable">查询</px-button>
          <px-button @click="resetTable">重置</px-button>
        </div>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 420px)" border>
        <!-- <px-table-column fixed="left" prop="workOrderCode" label="维修任务编号" min-width="230" show-overflow-tooltip />
        <px-table-column fixed="left" prop="workOrderName" label="维修任务名称" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <a @click="handleView(scope.row)">{{ scope.row.workOrderName }}</a>
          </template>
        </px-table-column> -->
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'status'" #default="scope">
            <div class="status">
              <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.workOrderStatus]}` }" />
              <p :style="{ color: `${tagBgColorList[scope.row.workOrderStatus]}` }">{{ scope.row.workOrderStatusDesc }}</p>
            </div>
          </template>
          <template v-else-if="item.type === 'code'" #default="scope">
            <span v-if="isHasPermission('ALL_EQUIP_MAINTAIN_TASK_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
              {{ scope.row.workOrderCode }}
            </span>
            <span v-else>{{ scope.row.workOrderCode }}</span>
          </template>
          <template v-else-if="item.type === 'link'" #default="scope">
            <span v-if="isHasPermission('ALL_EQUIP_MAINTAIN_TASK_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
              {{ scope.row.workOrderName }}
            </span>
            <span v-else>{{ scope.row.workOrderName }}</span>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip v-if="scope.row.workOrderStatus !== 0" content="详情" placement="top">
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[0, 2].includes(scope.row.workOrderStatus) && [0, 1].includes(activeName)" content="编辑" placement="top">
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="[1].includes(scope.row.workOrderStatus) && userId === scope.row.createBy && [0, 1].includes(activeName)"
              content="撤回"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_BACK'" link type="primary" icon="Rollback" @click="handleBack(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.workOrderStatus === 0" content="删除" placement="top">
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_DELETE'" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
            <!--发起人取消任务-->
            <px-tooltip
              v-if="scope.row.workOrderStatus == 3 && userId === scope.row.createBy && [0, 1].includes(activeName)"
              content="取消任务"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_CANCEL'" link type="primary" icon="CircleClose" @click="handleCancelCreate(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="[3].includes(scope.row.workOrderStatus) && scope.row.isInGroup && [0, 3].includes(activeName)"
              content="领取任务"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_COLLECT'" link type="primary" icon="DocumentAdd" @click="handleCollect(scope.row)" />
            </px-tooltip>
            <!--执行人取消任务-->
            <px-tooltip
              v-if="[3].includes(scope.row.workOrderStatus) && scope.row.isInGroup && [0, 3].includes(activeName)"
              content="退回任务"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_CANCEL'" link type="primary" icon="Rollback" @click="handleCollect(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="[1].includes(scope.row.workOrderStatus) && userId === scope.row.approverId && [0, 2].includes(activeName)"
              content="审核"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_AUDIT'" link type="primary" @click="handleAudit(scope.row)">
                <component :is="markRaw(stamp)" />
              </px-button>
            </px-tooltip>
            <px-tooltip
              v-if="[5].includes(scope.row.workOrderStatus) && userId === scope.row.supervisorId && [0, 2].includes(activeName)"
              content="验收"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_AUDIT'" link type="primary" @click="handleAudit(scope.row)">
                <component :is="markRaw(stamp)" />
              </px-button>
            </px-tooltip>
            <px-tooltip
              v-if="
                scope.row.workOrderStatus == 8 && userId === scope.row.executorId && scope.row.isFinishMaterial == 0 && [0, 3].includes(activeName)
              "
              content="资料补充"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_FILE'" link type="primary" icon="FileAdd" @click="handleAddFile(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="[4, 6].includes(scope.row.workOrderStatus) && userId === scope.row.executorId && [0, 3].includes(activeName)"
              content="执行任务"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_TASK_EXECUTE'" link type="primary" icon="DocumentChecked" @click="handleExecute(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 新增页面 -->
    <AddMaintainTask
      :isMain="isMain"
      :isView="isView"
      :taskId="taskId"
      :drawerType="drawerType"
      :orderCode="orderCode"
      :workOrderCode="workOrderCode"
      :shareData="{ faultTypeList, faultSourceList, faultLevelList }"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <AuditMaintainTask v-show="isView" @handleGoToEdit="handleGoToEdit" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_MAINTAIN_TASK"
});
import { queryDictData } from "@/api/common";
import {
  backMaintainList,
  cancelMaintainList,
  delMaintainList,
  getMaintainList,
  getWorkOrderStatusList,
  queryFaultTypeTree
} from "@/api/equip/maintain";
import stamp from "@/assets/svg/operation/stamp.svg?component";
import { isHasPermission } from "@/utils/auth";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { nextTick } from "process";
import { PxMessage, PxMessageBox } from "px-ui";
import { markRaw, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import AddMaintainTask from "./components/AddMaintainTask.vue";
import AuditMaintainTask from "./components/AuditMaintainTask.vue";
import CustomTabs from "./components/Tabs.vue";

const router = useRouter();
const route = useRoute();

const searchFormRef = ref();
const cascaderRef = ref();

const state = reactive<any>({
  userId: "",
  isMain: true, // 主页面true 详情页面false
  isView: false, // 查看true 新增/编辑false
  queryParams: {
    workOrderType: 0,
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "workOrderCode", label: "维修任务编号", type: "code", minWidth: "180", showOverflowTooltip: true, fixed: "left" },
    { prop: "workOrderName", label: "维修任务名称", type: "link", minWidth: "180", showOverflowTooltip: true },
    { prop: "workOrderStatusDesc", label: "维修状态", minWidth: "90", type: "status", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "60", showOverflowTooltip: true },
    { prop: "systemCodeDesc", label: "系统", minWidth: "100", showOverflowTooltip: true },
    { prop: "eqpId", label: "设备编号", minWidth: "100", showOverflowTooltip: true },
    { prop: "eqpName", label: "设备名称", minWidth: "100", showOverflowTooltip: true },
    { prop: "faultTypeDesc", label: "故障类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "faultLevelDesc", label: "故障等级", minWidth: "80", showOverflowTooltip: true },
    // { prop: "maintenanceSourceDesc", label: "来源", minWidth: "60", showOverflowTooltip: true },
    { prop: "createName", label: "报修人", minWidth: "100", showOverflowTooltip: true },
    { prop: "createTime", label: "报修时间", minWidth: "100", showOverflowTooltip: true },
    { prop: "approverName", label: "审批人", minWidth: "100", showOverflowTooltip: true },
    { prop: "opsGroupName", label: "执行报修组", minWidth: "150", showOverflowTooltip: true },
    { prop: "executorName", label: "执行人", minWidth: "120", showOverflowTooltip: true },
    { prop: "completionTime", label: "完成维修时间", minWidth: "110", showOverflowTooltip: true },
    { prop: "supervisorName", label: "验收人", minWidth: "100", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  drawerType: "add",
  taskId: "",
  systemCodes: [],
  faultTypeList: [],
  faultLevelList: [],
  faultSourceList: [],
  statusList: [], // 工单状态
  taskData: {},
  activeName: 0,
  orderCode: "" // 其他页面跳转过来的关联单号
});
const {
  userId,
  isMain,
  isView,
  queryParams,
  tableColumns,
  tableData,
  total,
  drawerType,
  taskId,
  systemCodes,
  faultTypeList,
  faultLevelList,
  faultSourceList,
  statusList,
  taskData,
  activeName,
  orderCode
} = toRefs(state);

const tabList = ref([
  { name: 0, label: "全部" },
  { name: 1, label: "我发起的" },
  { name: 3, label: "我执行的" },
  { name: 2, label: "我审批的" }
]);

const tagBgColorList = {
  0: "#909399", // 草稿
  1: "#F59E0B", // 待审批
  2: "#EF4444", // 审批驳回
  3: "#F59E0B", // 待接单
  4: "#3B82F6", // 执行中
  5: "#F59E0B", // 待验收
  6: "#EF4444", // 验收驳回
  7: "#909399", // 取消
  8: "#10B981" // 已完成
};

const handleTypeChange = () => {
  cascaderRef.value.togglePopperVisible();
};
const handelTabSelected = () => {
  searchFormRef.value.resetFields();
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  nextTick(() => {
    queryTable();
  });
};

// 获取科室下拉列表
const queryClassNameSelect = async () => {
  const tempLevelList = await queryDictData({ typeCode: "FAULT_LEVEL" });
  faultLevelList.value = tempLevelList || [];
  const tempSourceList = await queryDictData({ typeCode: "MAINTENANCE_SOURCE" });
  faultSourceList.value = tempSourceList || [];
  statusList.value = await getWorkOrderStatusList();
  faultTypeList.value = await queryFaultTypeTree();
};

// 查询列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  params.systemCodes = systemCodes.value;
  const data = await getMaintainList({ workOrderType: activeName.value, ...params });
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
};
// 重置筛选条件列表
const resetTable = async () => {
  searchFormRef.value.resetFields();
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  queryTable();
};

// 进入页面时触发
onMounted(async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  const { id, tabName, exception, type, status, className } = route.query;
  // 列表筛选
  if (type === "list") {
    // queryParams.value.workOrderStatus = status;
    queryParams.value.workOrderStatusList = status ? (status as string)?.split("-") : [];
    queryParams.value.className = className;
  }
  if (id) {
    isMain.value = false;
    isView.value = true;
  }
  if (tabName) {
    activeName.value = +tabName;
    handelTabSelected();
  }
  if (exception) {
    drawerType.value = "exception";
    orderCode.value = exception;
    isMain.value = false;
    isView.value = false;
  }
  queryTable();
  queryClassNameSelect();
});
// 详情
const handleView = (row: any) => {
  router.push(
    `/all/equip/maintain/task?id=${row.id}&workOrderCode=${row.workOrderCode}&status=${row.workOrderStatus}&type=view&tabName=${activeName.value}`
  );
};
// 领取任务
const handleCollect = (row: any) => {
  router.push(`/all/equip/maintain/task?id=${row.id}&status=${row.workOrderStatus}&type=collect&tabName=${activeName.value}`);
};
// 审核/验收任务
const handleAudit = (row: any) => {
  router.push(`/all/equip/maintain/task?id=${row.id}&status=${row.workOrderStatus}&type=audit&tabName=${activeName.value}`);
};
// 执行任务
const handleExecute = (row: any) => {
  router.push(`/all/equip/maintain/task?id=${row.id}&status=${row.workOrderStatus}&type=execute&tabName=${activeName.value}`);
};
// 资料补充
const handleAddFile = (row: any) => {
  router.push(`/all/equip/maintain/task?id=${row.id}&status=${row.workOrderStatus}&type=file&tabName=${activeName.value}`);
};
// 添加
const handleAdd = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};
// 编辑
const workOrderCode = ref();
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  taskId.value = row.id;
  workOrderCode.value = row.workOrderCode;
  isMain.value = false;
  isView.value = false;
};
const handleGoToEdit = val => {
  console.log("传递", val);
  // drawerType.value = "edit";
  // taskId.value = val;
  // isMain.value = false;
  // isView.value = false;
};
const handleCancelCreate = (row: any) => {
  PxMessageBox.confirm(`确认取消维修任务吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await cancelMaintainList({ id: row.id });
      PxMessage.success("取消成功");
      queryTable();
    })
    .catch(() => {});
};
const handleBack = row => {
  PxMessageBox.confirm(`确认撤回维修任务吗？撤回后任务回归为草稿`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await backMaintainList({ id: row.id });
      PxMessage.success("撤回成功");
      queryTable();
    })
    .catch(() => {});
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`请确认是否删除该草稿，删除后不可恢复`, "草稿删除确认", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delMaintainList({ id: row.id });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  taskData.value = {};
  taskId.value = "";
  isMain.value = true;
  drawerType.value = "";
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
